#include "musicplayer.h"
#include "ui_musicplayer.h"
#include<QPushButton>
#include<QMouseEvent>
#include<QGraphicsDropShadowEffect>
#include<QDebug>
#include<QJsonObject>
#include<QJsonArray>
#include<QPoint>
#include<QFileDialog>
#include<QMediaPlaylist>
#include<QMessageBox>
#include<QSqlQuery>
#include <QSqlError>
#include<QSystemTrayIcon>
#include<QMenu>
#include<QStandardPaths>


MusicPlayer::MusicPlayer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MusicPlayer),
      currentIndex(-1)
{
    ui->setupUi(this);
    initui();
    initSqlite();
    initMusicList();
    initPlayer();
    connectSignalAndSlots();


}

MusicPlayer::~MusicPlayer()
{
    delete ui;
}

void MusicPlayer::initui()
{
    this->setWindowFlag(Qt::FramelessWindowHint);

    setAttribute(Qt::WA_TranslucentBackground);
    QGraphicsDropShadowEffect*shadowEffect=new QGraphicsDropShadowEffect(this);

    setWindowIcon(QIcon(":/images/tubiao.png"));
    shadowEffect->setOffset(0,0);
    shadowEffect->setColor("#000000");
    shadowEffect->setBlurRadius(10);
    this->setGraphicsEffect(shadowEffect);

    QSystemTrayIcon *trayIcon=new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/images/tubiao.png"));
    trayIcon->show();

    QMenu*trayMenu=new QMenu();
    trayMenu->addAction("显示",this,&QWidget::showNormal);
    trayMenu->addAction("退出",this,&MusicPlayer::MusicPlayerQuit);
    trayIcon->setContextMenu(trayMenu);

    //设置BtForm图标，文本
    ui->Rec->setIconAndText(":/images/rec.png","推荐",0);
    ui->radio->setIconAndText(":/images/radio.png","电台",1);
    ui->music->setIconAndText(":/images/music.png","音乐馆",2);
    ui->like->setIconAndText(":/images/like.png","我喜欢",3);
    ui->local->setIconAndText(":/images/local.png","本地下载",4);
    ui->recent->setIconAndText(":/images/recent.png","最近播放",5);



    ui->stackedWidget->setCurrentIndex(4);
    currentPage=ui->localPage;

    //初始化推荐页面
    srand(time(NULL));

     ui->recMusicBox->initRecBoxUi(randomPiction(),1);
     ui->supplyMusicBox->initRecBoxUi(randomPiction(),2);


     //设置CommonPage信息

     ui->likePage->setCommonUi("我喜欢",":/images/ilikebg.png");


     ui->localPage->setCommonUi("本地音乐",":/images/localbg.png");


     ui->recentPage->setCommonUi("最近播放",":/images/recentbg.png");




     ui->play->setIcon(QIcon(":images/play_2.png"));
     ui->playMode->setIcon(QIcon(":/images/shuffle_2.png"));
     volumeTool =new VolumeTool(this);

    lrcPage=new LrcPage(this);
    lrcPage->setGeometry(10,10,lrcPage->width(),lrcPage->height());
    lrcPage->hide();

    lrcPageAnimal=new QPropertyAnimation(lrcPage,"geometry",this);
    lrcPageAnimal->setDuration(250);
    lrcPageAnimal->setStartValue(QRect(10,10+lrcPage->height(),lrcPage->width(),lrcPage->height()));
    lrcPageAnimal->setEndValue(QRect(10,10,lrcPage->width(),lrcPage->height()));

}

void MusicPlayer::initSqlite()
{
    sqlite=QSqlDatabase::addDatabase("QSQLITE");
    sqlite.setDatabaseName("MusicPlayer.db");

    if(!sqlite.open()){
        QMessageBox::critical(this,"MusicPlayer","数据库打开失败");
        return;
    }

    QString sql="create table if not exists MusicInfo(\
                id integer primary key autoincrement,\
                musicId varchar(50) unique,\
                musicName varchar(50),\
                musicSinger varchar(50),\
                albumName varchar(50),\
                musicUrl varchar(256),\
                duration bigint,\
                isLike integer,\
                isHistory integer)";

    QSqlQuery query;
    if (!query.exec(sql)) {
        QMessageBox::critical(this, "MusicPlay", "初始化错误：" + query.lastError().text());
        return;
    }
    qDebug()<<"创建表成功";

}

void MusicPlayer::initMusicList()
{
    musicList.readFromDB();

    ui->likePage->setMusicListType(LIKE_LIST);
    ui->likePage->reFresh(musicList);

    ui->localPage->setMusicListType(LOCAL_LIST);
    ui->localPage->reFresh(musicList);

    ui->recentPage->setMusicListType(HISTORY_LIST);
    ui->recentPage->reFresh(musicList);


}

void MusicPlayer::connectSignalAndSlots()
{
    connect(ui->Rec,&BtForm::btClick,this,&MusicPlayer::onBtFormClick);//设置点不同按钮，切换界面
    connect(ui->radio,&BtForm::btClick,this,&MusicPlayer::onBtFormClick);
    connect(ui->music,&BtForm::btClick,this,&MusicPlayer::onBtFormClick);
    connect(ui->like,&BtForm::btClick,this,&MusicPlayer::onBtFormClick);
    connect(ui->local,&BtForm::btClick,this,&MusicPlayer::onBtFormClick);
    connect(ui->recent,&BtForm::btClick,this,&MusicPlayer::onBtFormClick);

    connect(ui->likePage,&CommonPage::updateLikeMusic,this,&MusicPlayer::updateLikeMusicAndPage);
    connect(ui->localPage,&CommonPage::updateLikeMusic,this,&MusicPlayer::updateLikeMusicAndPage);
    connect(ui->recentPage,&CommonPage::updateLikeMusic,this,&MusicPlayer::updateLikeMusicAndPage);
    connect(ui->play,&QPushButton::clicked,this,&MusicPlayer::onPlayMusic);
    connect(ui->playUp,&QPushButton::clicked,this,&MusicPlayer::onPlayUpClicked);
    connect(ui->playDown,&QPushButton::clicked,this,&MusicPlayer::onPlayDownClicked);
    connect(ui->playMode,&QPushButton::clicked,this,&MusicPlayer::onPlaybackModeClicked);
    connect(ui->likePage,&CommonPage::playAll,this,&MusicPlayer::onPlayAll);

    connect(ui->likePage,&CommonPage::playMusicByIndex,this,&MusicPlayer::playMusicByIndex);
    connect(ui->localPage,&CommonPage::playMusicByIndex,this,&MusicPlayer::playMusicByIndex);
    connect(ui->recentPage,&CommonPage::playMusicByIndex,this,&MusicPlayer::playMusicByIndex);
    connect(ui->netPage,&CommonPage::playMusicByIndex,this,&MusicPlayer::playMusicByIndex);

    connect(volumeTool,&VolumeTool::setMusicMuted,this,&MusicPlayer::setPlayMuted);
    connect(ui->pushButton,&QPushButton::clicked,this,&MusicPlayer::onLrcWordClicked);

    connect(ui->recMusicBox,&RecBox::netMusicListready, this, &MusicPlayer::onNetMusicListReady);

}

QJsonArray MusicPlayer::randomPiction()
{
    QVector<QString> vecImageName;
    for(int i=1;i<=40;i++){
        if(i==2)continue;
        QString tmp=QString::asprintf("%03d.png",i);
        vecImageName<<tmp;
    }

    std::random_shuffle(vecImageName.begin(),vecImageName.end());
    for(auto i:vecImageName){
        qDebug()<<i<<" ";
    }

    QJsonArray objArray;
    for(int i=0;i<vecImageName.size();i++){
        QJsonObject obj;
        obj.insert("path",":/images/rec/"+vecImageName[i]);
        QString strText=QString("推荐-%1").arg(i,3,10,QChar('0'));
        obj.insert("text",strText);

        objArray.append(obj);
    }

    return objArray;
}

void MusicPlayer::initPlayer()
{
    player=new QMediaPlayer(this);
    playList=new QMediaPlaylist(this);
    //设置默认模式
    playList->setPlaybackMode(QMediaPlaylist::Random);
    //将播放列表设置道播放媒体对象中
    player->setPlaylist(playList);
    //设置默认音量
    player->setVolume(20);

    connect(player,&QMediaPlayer::stateChanged,this,&MusicPlayer::onPlayStateChanged);
    connect(playList,&QMediaPlaylist::playbackModeChanged,this,&MusicPlayer::onPlaybackModeChanged);
    connect(playList,&QMediaPlaylist::currentIndexChanged,this,&MusicPlayer::onCurrentIndexChanged);
    connect(player,&QMediaPlayer::durationChanged,this,&MusicPlayer::onDurationChanged);
    connect(player,&QMediaPlayer::positionChanged,this,&MusicPlayer::onPositionChanged);
    connect(ui->progressBar,&MusicSlider::setMusicSliderPosition,this,&MusicPlayer::onMusicSliderChanged);
    connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&MusicPlayer::onMetaDataAvailableChanged);
    connect(this,&MusicPlayer::playingMusicChanged,this,&MusicPlayer::onMetaDataAvailableChanged);

}

void MusicPlayer::onPlayStateChanged()
{
    if(player->state()==QMediaPlayer::PlayingState){
        ui->play->setIcon(QIcon(":/images/play_on.png"));
    }
    else{
        ui->play->setIcon(QIcon(":/images/play3.png"));
    }
}

QString MusicPlayer::cacheFilePath(const QString &url)
{

        QByteArray hash=QCryptographicHash::hash(url.toUtf8(),QCryptographicHash::Md5);

        QString filename=QString(hash.toHex())+".jpg";

        QString cacheDir=QStandardPaths::writableLocation(QStandardPaths::CacheLocation);

        QDir().mkpath(cacheDir);

        return QDir(cacheDir).filePath(filename);

}


void MusicPlayer::on_quit_clicked()
{
    hide();
}

void MusicPlayer::onBtFormClick(int pageId)
{
    QList<BtForm*> btFormList = this->findChildren<BtForm*>();
    for(auto btForm:btFormList){
        if(btForm->getPageId()!=pageId){
            btForm->clearBackground();
        }
    }
    ui->stackedWidget->setCurrentIndex(pageId);

}

void MusicPlayer::mousePressEvent(QMouseEvent *event)
{
    if(Qt::LeftButton==event->button()){
        dragPosition= event->globalPos()-geometry().topLeft();
    }
}

void MusicPlayer::mouseMoveEvent(QMouseEvent *event)
{
    if(Qt::LeftButton==event->buttons()){
        move(event->globalPos()-dragPosition);
    }
}





void MusicPlayer::on_volume_clicked()
{
    //获取音量键的全局坐标
    QPoint point=ui->volume->mapToGlobal(QPoint(0,0));

    QPoint volumeLeftTop=point-QPoint(volumeTool->width()/2-15,volumeTool->height()-10);

    volumeTool->move(volumeLeftTop);
    volumeTool->show();
}

void MusicPlayer::on_addLocal_clicked()
{
    QFileDialog fileDialog(this);
    fileDialog.setWindowTitle("添加本地下载音乐");


    QDir dir(QDir::currentPath());
    dir.cdUp();
    QString projectPath=dir.path()+"/music_player";


    fileDialog.setDirectory(projectPath);

    fileDialog.setFileMode(QFileDialog::ExistingFiles);

//    fileDialog.setNameFilter("代码文件(*.h)");
//    fileDialog.setNameFilter("代码文件(*.h *cpp)");
    QStringList mimeTypeFilters;
    mimeTypeFilters<<"application/octet-stream";
    fileDialog.setMimeTypeFilters(mimeTypeFilters);

    if(QDialog::Accepted==fileDialog.exec()){

        QList<QUrl> fileUrls=fileDialog.selectedUrls();

//        int a=1;
//        for(auto i:fileUrls){
//            qDebug()<<i;
//            qDebug()<<a++;
//        }
        //fileUrls里面存放刚刚选择的音乐

        musicList.addMusicByUrl(fileUrls);

        ui->stackedWidget->setCurrentIndex(4);

        ui->localPage->reFresh(musicList);
        ui->localPage->addMusicToPlaylist(musicList,playList);
    }

}

void MusicPlayer::updateLikeMusicAndPage(bool isLike, const QString &musicId)
{
    auto it=musicList.findMusicByMusicId(musicId);
    if(it!=musicList.end()){
        it->setIsLike(isLike);
    }

    ui->likePage->reFresh(musicList);
    ui->localPage->reFresh(musicList);
    ui->recentPage->reFresh(musicList);
}

//播放音乐

void MusicPlayer::onPlayMusic()
{
    if(QMediaPlayer::PlayingState==player->state()){
        player->pause();
//        ui->play->setIcon(QIcon(":/images/play3.png"));
    }
    else if(QMediaPlayer::PausedState==player->state()){
        player->play();
//        ui->play->setIcon(QIcon(":/images/play_on.png"));
    }
    else if(QMediaPlayer::StoppedState==player->state()){
        player->play();
//        ui->play->setIcon(QIcon(":/images/play_on.png"));
    }
}

void MusicPlayer::onPlayUpClicked()
{
    playList->previous();
}

void MusicPlayer::onPlayDownClicked()
{
    playList->next();
}

void MusicPlayer::onPlaybackModeClicked()
{
    if(playList->playbackMode()==QMediaPlaylist::Loop){
        playList->setPlaybackMode(QMediaPlaylist::Random);
        ui->playMode->setToolTip("随机播放");
    }
    else if(playList->playbackMode()==QMediaPlaylist::Random){
        playList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
        ui->playMode->setToolTip("单曲循环");
    }
    else if(playList->playbackMode()==QMediaPlaylist::CurrentItemInLoop){
        playList->setPlaybackMode(QMediaPlaylist::Loop);
        ui->playMode->setToolTip("列表循环");
    }
    else{
        qDebug()<<"暂不支持";
    }
}

void MusicPlayer::onPlaybackModeChanged(QMediaPlaylist::PlaybackMode playbackMode)
{
    if(playbackMode==QMediaPlaylist::Loop){
        ui->playMode->setIcon(QIcon(":/images/list_play.png"));
    }
    else if(playbackMode==QMediaPlaylist::Random){
        ui->playMode->setIcon(QIcon(":/images/shuffle_2.png"));
    }
    else if(playbackMode==QMediaPlaylist::CurrentItemInLoop){
        ui->playMode->setIcon(QIcon(":/images/single_play.png"));
    }
}

void MusicPlayer::onPlayAll(MusicListType musicListType)
{
    CommonPage* page=ui->localPage;

    switch(musicListType){
    case LIKE_LIST:
        page=ui->localPage;
        break;
    case LOCAL_LIST:
         page=ui->localPage;
        break;
    case HISTORY_LIST:
            page=ui->recentPage;
            break;
    case NET_LIST:
            page=ui->netPage;
    }


    playAllMusicOfCommonPage(page,0);
}

void MusicPlayer::playAllMusicOfCommonPage(CommonPage *page, int index)
{
    currentPage=page;

    qDebug()<<"当前页面类型:"<<currentPage->getPageListType();
    playList->clear();
    for(auto i:musicList){
        qDebug()<<"歌单里的url:"<<i.getMusicUrl();

    }
    page->addMusicToPlaylist(musicList,playList);
    playList->setCurrentIndex(index);
    emit playingMusicChanged();
    player->play();
}

void MusicPlayer::playMusicByIndex(CommonPage *page, int index)
{
    qDebug()<<page;
    playAllMusicOfCommonPage(page,index);
}

void MusicPlayer::onCurrentIndexChanged(int index)
{
    currentIndex=index;
    QString musicId=currentPage->getMusicIdByIndex(index);
    auto it=musicList.findMusicByMusicId(musicId);
    if(it!=musicList.end()){
        it->setIsHistory(1);
    }
    ui->recentPage->reFresh(musicList);
}

void MusicPlayer::setPlayMuted(bool isMuted)
{
    player->setMuted(isMuted);
}

void MusicPlayer::onDurationChanged(qint64 duration)
{
    totalTime=duration;
    int min=duration/1000/60;
    int sec=duration/1000%60;
    ui->totaltime->setText(QString("%1:%2").arg(min,2,10,QChar(0)).arg(sec,2,10,QChar('0')));
}

void MusicPlayer::onPositionChanged(qint64 position)
{
    int min=position/1000/60;
    int sec=position/1000%60;
    ui->time->setText(QString("%1:%2/").arg(min,2,10,QChar(0)).arg(sec,2,10,QChar('0')));

    ui->progressBar->setStep(position/(float)totalTime);

    if(currentIndex>=0){
        lrcPage->showLrcWordLine(position);
    }

}

void MusicPlayer::onMusicSliderChanged(float ration)
{
    qint64 duration=totalTime*ration;
    int min=duration/1000/60;
    int sec=duration/1000%60;
    ui->time->setText(QString("%1:%2").arg(min,2,10,QChar(0)).arg(sec,2,10,QChar('0')));
    player->setPosition(duration);
}

void MusicPlayer::onMetaDataAvailableChanged()
{
    QString musicId=currentPage->getMusicIdByIndex(currentIndex);
    auto it=musicList.findMusicByMusicId(musicId);
    QString musicName("未知歌曲");
    QString musicSinger("未知歌手");
    if(it!=musicList.end()){
        musicName=it->getMusicName();
        musicSinger=it->getMusicSinger();
    }
    ui->musicName->setText(musicName);
    ui->musicSinger->setText(musicSinger);
    QVariant coverimage=player->metaData("ThumbnailImage");
    if(coverimage.isValid()){
        QImage image=coverimage.value<QImage>();
        ui->musicCover->setPixmap(QPixmap::fromImage(image));
        currentPage->setMusicImage(QPixmap::fromImage(image));

    }
    else{
        //无封面图
        //设置默认图片，待完成
        QString path=":/images/rec/001.png";
        ui->musicCover->setPixmap(path);
        currentPage->setMusicImage(path);
    }
    ui->musicCover->setScaledContents(true);

//    qDebug()<<it->getMusicName()<<"  "<<it->getMusicUrl();
    if(it!=musicList.end()){
        QString lrcPath=it->getLrcFilePath();

//        qDebug()<<"歌词地址是："<<lrcPath;
        lrcPage->setName(it->getMusicName());
        lrcPage->setSinger(it->getMusicSinger());
        lrcPage->parseLrcFile(lrcPath);
    }
}

void MusicPlayer::onLrcWordClicked()
{
    lrcPage->show();
    lrcPageAnimal->start();
}

void MusicPlayer::on_min_clicked()
{
    showMinimized();
}

void MusicPlayer::on_max_clicked()
{
    QMessageBox::information(this,"不好意思","这个功能做起来好麻烦，先省略掉捏～");
}

void MusicPlayer::MusicPlayerQuit()
{
    musicList.writeToMusicDB();
    sqlite.close();
    close();
}

void MusicPlayer::onNetMusicListReady(MusicList netlist, QString listName)
{
    ui->netPage->setMusicListType(NET_LIST);

    QString coverUrl= QString("http://127.0.0.1:8080/cover/%1.jpg").arg(listName);

    qDebug()<<"coverUrl:"<<coverUrl;

    if (g_cover_cache.contains(coverUrl)) {
        QPixmap pix = g_cover_cache[coverUrl];
        ui->netPage->setCommonUi_Net(listName, pix); // 先设置标题
            // 自己写个接口，直接传 QPixmap
    } else {
        QString localPath=cacheFilePath(coverUrl);

        if(QFile::exists(localPath)){
            QPixmap pix(localPath);
            if(!pix.isNull()){
                qDebug()<<"从磁盘中加载图片1"<<localPath;

                ui->netPage->setCommonUi_Net(listName, pix);
            }
        }   // 🔹 这里是 QFile::exists(localPath) 的 if 对应的 }
    }       // 🔹 这里是 else 的 }

    for(auto i:netlist){
        qDebug()<<"有歌曲:"<<i.getMusicName();
        musicList.push_back(i);
    }


    ui->netPage->reFresh(musicList);
    int index = ui->stackedWidget->indexOf(ui->netPage);
    ui->stackedWidget->setCurrentIndex(index);
    currentPage = ui->netPage;
}

